package org.example.chat.client;


import org.example.chat.common.Message;
import org.example.chat.common.MessageType;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;

public class ClientThreadConnectServer implements Runnable {

    private Socket socket;
    private String userId;

    public ClientThreadConnectServer(Socket socket) {
        this.socket = socket;
    }

    public ClientThreadConnectServer(String userId, Socket socket) {
        this.socket = socket;
        this.userId = userId;
    }

    public Socket getSocket() {
        return socket;
    }

    @Override
    public void run() {
        while (true) {
//            synchronized (this) {
            try {
                System.out.println("客户端线程，一直等待读取从服务端发送过来的消息...");
                InputStream inputStream = null;
                inputStream = socket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(inputStream);
                Message message = (Message) ois.readObject();
                //根据服务端发送回来的消息类型做判断
                String msgType = message.getMsgType();

                if (msgType.equals(MessageType.ONLINE_USERS.getCode())) {
                    String[] s = message.getContent().split(" ");
                    System.out.println("\n=======当前在线用户列表========");
                    System.out.println("用户： " + Arrays.asList(s));
                } else if (msgType.equals(MessageType.PUBLIC_CHAT.getCode())) {
                    String sender = message.getSender();
                    String content = message.getContent();
                    System.out.println("发送人： " + sender + "在村里大喇叭对大家说： " + content);
                } else if (msgType.equals(MessageType.PRIVATE_CHAT.getCode())) {
                    //接收服务端的回复
                    System.out.println("发送人: " + message.getSender() + "发送给: " + message.getReceiver() + "消息: " + message.getContent());
                } else if (msgType.equals(MessageType.SEND_FILE.getCode())) {
                    System.out.println("发送人： " + message.getSender() + " 发送源文件： "
                            + message.getSrcFile() + " 给： " + message.getReceiver() +"到目的地目录 "+message.getDestFile());
                } else if (msgType.equals(MessageType.EXIT_SYSTEM.getCode())) {
                    System.out.println("客户端： " + message.getSender() + " 退出啦 ");
                } else {
                    System.out.println("no this message type");
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}

//}
